//
//  QCNetworkManager.m
//  QCAppProject
//
//  Created by yjl on 2021/8/19.
//

#import "QCNetworkManager.h"

#define kRandomLength 32
static const NSString *kRandomAlphabet = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

@implementation QCNetworkManager


+ (NSURLSessionDataTask * _Nullable)extracted:(void (^)(CGFloat))Progressblock failure:(void (^)(NSError *))failure manager:(AFHTTPSessionManager *)manager parameters:(NSDictionary *)parameters success:(void (^)(id))success url:(NSString *)url {
    NSLog(@"============请求的参数：%@",parameters);
    return [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        CGFloat progress = (CGFloat)uploadProgress.completedUnitCount/(CGFloat)uploadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (Progressblock) {
                Progressblock(progress);
            }
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reWithUrl:url andResponseObject:responseObject success:success failure:failure];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errWithError:error url:url failure:failure];
        });
    }];
}

+ (NSURLSessionDataTask *)requestWithURL:(NSString *)url
                              parameters:(NSDictionary *)parameters
                                Progress:(void (^)(CGFloat progress))Progressblock
                                 success:(void(^)(id responseObject))success
                                 failure:(void(^)(NSError *error))failure
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    
    //登录以后有token，要使用token。
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

//    NSString *token = [UD objectForKey:kTokenKey];
//    if(token){
//        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
//    }
//    NSLog(@"token = %@",token);
    [manager.requestSerializer setValue:[self createId] forHTTPHeaderField:@"X-Request-ID"];
    manager.requestSerializer.timeoutInterval = 30;
    [manager.requestSerializer setValue:@"000013" forHTTPHeaderField:@"app_id"];

    [manager.requestSerializer requestWithMethod:@"POST" URLString:url parameters:parameters error:nil];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    
    //添加安全策略，及允许无效证书访问
    AFSecurityPolicy *security = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [security setValidatesDomainName:NO];
    security.allowInvalidCertificates = YES;
    manager.securityPolicy = security;
    
    
    NSURLSessionDataTask * task =  [self extracted:Progressblock failure:failure manager:manager parameters:parameters success:success url:url];
    
    return task;
}

+ (NSURLSessionDataTask *)requestWithURL:(NSString *)url
                              parameters:(NSDictionary *)parameters
                        constructingBody:(void(^)(id<AFMultipartFormData> formData))constructingBody
                                Progress:(void (^)(CGFloat progress))Progressblock
                                 success:(void(^)(id responseObject))success
                                 failure:(void(^)(NSError *error))failure
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    
    //登录以后有token，要使用token。
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    
    //添加安全策略，及允许无效证书访问
    AFSecurityPolicy *security = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [security setValidatesDomainName:NO];
    security.allowInvalidCertificates = YES;
    manager.securityPolicy = security;
    manager.requestSerializer.timeoutInterval = 60;
//    NSString *token = [UD objectForKey:kTokenKey];
//    if(token){
//        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
//    }
//    NSLog(@"token = %@",token);
    [manager.requestSerializer setValue:[self createId] forHTTPHeaderField:@"X-Request-ID"];
    [manager.requestSerializer setValue:@"000013" forHTTPHeaderField:@"app_id"];

    
    [manager.requestSerializer requestWithMethod:@"POST" URLString:url parameters:parameters error:nil];
    
    NSURLSessionDataTask * task =  [manager POST:url parameters:parameters headers:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        constructingBody(formData);
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        CGFloat progress = (CGFloat)uploadProgress.completedUnitCount/(CGFloat)uploadProgress.totalUnitCount;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (Progressblock) {
                Progressblock(progress);
            }
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reWithUrl:url andResponseObject:responseObject success:success failure:failure];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errWithError:error url:url failure:failure];
        });
    }];
    
    return task;
}


+(NSURLSessionDataTask *)getRequestWithURL:(NSString *)url
                                parameters:(NSDictionary *)parameters
                                  Progress:(void (^)(CGFloat))Progressblock
                                   success:(void (^)(id))success
                                   failure:(void (^)(NSError *))failure
{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    
    //登录以后有token，要使用token。
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    //添加安全策略，及允许无效证书访问
    AFSecurityPolicy *security = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [security setValidatesDomainName:NO];
    manager.requestSerializer.timeoutInterval = 30;
    security.allowInvalidCertificates = YES;
    manager.securityPolicy = security;
//    NSString *token = [UD objectForKey:kTokenKey];
//    if(token){
//        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
//    }
//    NSLog(@"token = %@",token);

//    [manager.requestSerializer setValue:[self createId] forHTTPHeaderField:@"X-Request-ID"];
//    [manager.requestSerializer setValue:@"000013" forHTTPHeaderField:@"app_id"];

    [manager.requestSerializer requestWithMethod:@"GET" URLString:url parameters:parameters error:nil];
    
    NSLog(@"============请求的参数：%@",parameters);
    NSURLSessionDataTask * task = [manager GET:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        CGFloat progress = (CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (Progressblock) {
                Progressblock(progress);
            }
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reWithUrl:url andResponseObject:responseObject success:success failure:failure];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errWithError:error url:url failure:failure];
        });
    }];
    return task;
    
    
}

+ (NSURLSessionDataTask *)auditRequestWithURL:(NSString *)url
            parameters:(NSDictionary *)parameters
              Progress:(void (^)(CGFloat progress))Progressblock
               success:(void(^)(id responseObject))success
                                      failure:(void(^)(NSError *error))failure{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    });
    
    //登录以后有token，要使用token。
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

//    NSString *token = [UD objectForKey:kTokenKey];
//    NSString *token = [FDDKeyChain getContentFromKeyChain:kTokenKey];
//    if(token){
//        [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
//    }
    [manager.requestSerializer setValue:[self createId] forHTTPHeaderField:@"X-Request-ID"];
    [manager.requestSerializer setValue:@"000013" forHTTPHeaderField:@"app_id"];
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", nil];
    
    //添加安全策略，及允许无效证书访问
    AFSecurityPolicy *security = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
    [security setValidatesDomainName:NO];
    security.allowInvalidCertificates = YES;
    manager.securityPolicy = security;
    
    NSURLSessionDataTask * task =  [manager POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        CGFloat progress = (CGFloat)uploadProgress.completedUnitCount/(CGFloat)uploadProgress.totalUnitCount;
        dispatch_async(dispatch_get_main_queue(), ^{
            if (Progressblock) {
                Progressblock(progress);
            }
        });
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reWithUrl:url andResponseObject:responseObject success:success failure:failure];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self errWithError:error url:url failure:failure];
        });
    }];
    
    return task;
}


+ (void)reWithUrl:(NSString *)url
andResponseObject:(id)responseObject
          success:(void(^)(id responseObject))success
          failure:(void(^)(NSError *error))failure{
    
    NSLog(@"===========================");
    NSLog(@"请求的url：%@",url);
    NSLog(@"返回的数据：%@",responseObject);
    NSLog(@"===========================");
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    });
    if ([[responseObject objectForKey:@"app_result_key"] integerValue] == 0) {
        success(responseObject);
    }
    else{
        
        NSString *code = responseObject[@"code"];
        NSDictionary *responseDict= responseObject;
        if ([responseDict.allKeys containsObject:@"system_result_message_key"]) {
            NSString *message =[responseDict objectForKey:@"system_result_message_key"];
            NSError *error = [NSError errorWithDomain:message code:[code integerValue] userInfo:nil];
            failure(error);
        } else {
            NSError *error = [NSError errorWithDomain:@"" code:[code integerValue] userInfo:nil];
            failure(error);
        }

        if ([code intValue] == LongTokenExpCode ||
            [code intValue] == TokenExpCode ||
            [code intValue] == 11091) {//消息列表跳详情，找不到文件，不弹提示，后台脏数据
            
        } else {
            if ([responseDict.allKeys containsObject:@"system_result_message_key"]) {
                [QCProgressHUD showHUDWithMessage:[responseDict objectForKey:@"system_result_message_key"] autoHide:YES];
            }
        }
//        //token跳转到登录界面
////        if([code intValue] == TokenExpCode){
////            [self presentLoginVC];
////        }
//
//        //1.会话token失效,如果启用了手势密码，进行手势密码验证
//        //2.会话token失效,如果没有启用了手势密码，跳转到登录界面重新登录
//        if ([self filterTokenExpToast:url]) {
//            return;
//        }
//        if([code intValue] == TokenExpCode){//会话token失效
//            if ([FDDUserConfigManager instance].isOpenGesture) {//启用了手势
//                if (![FDDGesManager shareInstance].requestCheckRefreshTokenOnce) {
//                    [FDDGesManager shareInstance].requestCheckRefreshTokenOnce = YES;
//                    [self checkRefreshToken];
//                }
//            } else {
//                [self presentLoginVC];
//            }
//        } else if([code intValue] == LongTokenExpCode){//长token失效
//            [self presentLoginVC];
//        }
//
    }
}

//#pragma mark - 跳到登录页
//+ (void)presentLoginVC {
//    [FDDToast showErrorWithMessage:@"登录时效过期"];
//    //清除本地数据
//    [[FDDSingleton instance] removeUserInfo];
//    NSLog(@"removeUserInforemoveUserInforemoveUserInfo");
//    FDDLoginViewController *login = [[FDDLoginViewController alloc]init];
//    FDDNavigationController *nav = [[FDDNavigationController alloc]initWithRootViewController:login];
//    FDDWindow.rootViewController = nav;
//}

//#pragma mark - 启用了手势, 跳到手势页，进行手势验证
//+ (void)presentGestureVC {
//    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
//    if ([appDelegate.currentViewController isKindOfClass:[FDDGesturesLoginViewController class]]) {
//       return;
//    }
//    if([appDelegate.currentViewController isKindOfClass:[FDDLoginViewController class]]){
//       [FDDToast showErrorWithMessage:@"登录时效过期"];
//       return;
//    }
//    FDDGesturesLoginViewController *gestureLogin = [FDDGesturesLoginViewController new];
//    gestureLogin.come = comeExpToken;
//    FDDNavigationController *nav = [[FDDNavigationController alloc]initWithRootViewController:gestureLogin];
//    FDDWindow.rootViewController = nav;
//}


+ (void)errWithError:(NSError *)error
                 url:(NSString *)url
             failure:(void(^)(NSError *error))failure{
    
    NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    NSLog(@"请求的url：%@",url);
    NSLog(@"错误：%@",error);
    NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    
    if (error.code == -999) {   //用户取消了请求
        
    }else{
        [QCProgressHUD showHUDWithMessage:@"网络异常，请稍后再试" autoHide:YES];
    }
    failure((NSError *)error);

    dispatch_async(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    });
}

#pragma mark - 创建随机数
+(NSString *)createId{
    NSMutableString *randomString = [NSMutableString stringWithCapacity:kRandomLength];
    for (int i = 0; i < kRandomLength; i++) {
        [randomString appendFormat: @"%C", [kRandomAlphabet characterAtIndex:arc4random_uniform((u_int32_t)[kRandomAlphabet length])]];
    }
    NSLog(@"randomString = %@", randomString);
    return randomString;
}

@end
